package com.cn.xiaonuo.slbfinances.stockcontrol.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cn.xiaonuo.common.constant.Status;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.DateUtils;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.members.entity.SlUser;
import com.cn.xiaonuo.slbfinances.members.mapper.SlUserMapper;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlbShop;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlShopMapper;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlOrder;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlOrderDetail;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlOrderDetailMapper;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlOrderMapper;
import com.cn.xiaonuo.slbfinances.stockcontrol.entity.SlOrderStream;
import com.cn.xiaonuo.slbfinances.stockcontrol.entity.SlShopStockControl;
import com.cn.xiaonuo.slbfinances.stockcontrol.entity.SlStoreInventoryTotal;
import com.cn.xiaonuo.slbfinances.stockcontrol.enums.FactoryStockEnum;
import com.cn.xiaonuo.slbfinances.stockcontrol.mapper.SlOrderStreamMapper;
import com.cn.xiaonuo.slbfinances.stockcontrol.mapper.SlShopStockControlMapper;
import com.cn.xiaonuo.slbfinances.stockcontrol.mapper.SlStoreInventoryTotalMapper;
import com.cn.xiaonuo.slbfinances.stockcontrol.param.InventoryChangeLogParam;
import com.cn.xiaonuo.slbfinances.stockcontrol.param.PageExclusiveShopParam;
import com.cn.xiaonuo.slbfinances.stockcontrol.param.PageStockLogParam;
import com.cn.xiaonuo.slbfinances.stockcontrol.service.SlShopStockControlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @BelongsProject: slb-reports-java
 * @Author: likui
 * @CreateTime: 2023-01-10  15:37
 * @Description: TODO
 */
@Service
@Slf4j
public class SlShopStockControlServiceImpl implements SlShopStockControlService {
    @Autowired
    private SlOrderMapper slOrderMapper;
    @Autowired
    private SlShopMapper slShopMapper;
    @Autowired
    private SlShopStockControlMapper slShopStockControlMapper;
    @Autowired
    private SlStoreInventoryTotalMapper slStoreInventoryTotalMapper;
    @Autowired
    private SlOrderStreamMapper slOrderStreamMapper;
    @Autowired
    private SlOrderDetailMapper slOrderDetailMapper;
    @Autowired
    private SlUserMapper slUserMapper;

    /**
     * 提供精确的小数位四舍五入处理
     *
     * @param v     需要四舍五入的数字
     * @param scale 小数点后保留几位
     * @return 四舍五入后的结果
     */
    public static BigDecimal round(BigDecimal v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(String.valueOf(v));
        return b.setScale(scale, BigDecimal.ROUND_HALF_UP);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage regularStockStatistics() {
        BusinessMessage message = new BusinessMessage();
        log.info("定时同步库存管理任务执行开始!");
        //当前日期减一天
        String createTime = DateUtils.datePlusMinus(-1);
        try {
            //查询专卖店库存变动涉及商品及店铺
            List<Map<String, Object>> storeInvolved = slOrderStreamMapper.getStoreInvolved(createTime);
            for (Map shopId : storeInvolved) {
                //出库总数
                Map<String, Object> totalIssue = slOrderStreamMapper.totalIssue(Convert.toInt(shopId.get("shopId")), createTime,1);
                //入库总数
                Map<String, Object> totalWarehousing = slOrderStreamMapper.totalWarehousing(Convert.toInt(shopId.get("shopId")), createTime,1);
                QueryWrapper<SlOrderStream> queryWrapper = this.streamQueryWrapper(shopId,createTime);
                List<SlOrderStream> orderStreams = slOrderStreamMapper.selectList(queryWrapper);
                //库存总金额
                BigDecimal stockTotalAmount=new BigDecimal(0);
                int stock=0;
                SlOrderStream slOrderStream=new SlOrderStream();
                for (SlOrderStream orderStream:orderStreams){
                    log.info("操作数据为：店铺id[{}]，规格id{}",shopId.get("shopId"),orderStream.getRepoSpecId());
                    //查询每日的最后一条作为当天的当前数量
                    SlOrderStream lastUpdateData = slOrderStreamMapper.getLastUpdateData(Convert.toInt(shopId.get("shopId")),orderStream.getRepoSpecId(),createTime, 1);
                    BigDecimal round = round(lastUpdateData.getCostPrice().multiply(Convert.toBigDecimal(lastUpdateData.getRepoCountAf())), 2);
                    stockTotalAmount=stockTotalAmount.add(round);
                    stock+=lastUpdateData.getRepoCountAf();
                    slOrderStream.setShopId(lastUpdateData.getShopId());
                    slOrderStream.setShopName(lastUpdateData.getShopName());
                    slOrderStream.setCreateTime(lastUpdateData.getCreateTime());
                }
                slOrderStream.setRepoCountAf(stock);
                //添加专卖店合计数据
                this.addInventoryTotalData(slOrderStream, totalIssue, totalWarehousing, stockTotalAmount, 1);
                List<SlOrderStream> slOrderStreams = this.getOrderStream(shopId,createTime,1);
                for (SlOrderStream orderStream : slOrderStreams) {
                    this.addStockControlData(orderStream, FactoryStockEnum.STORE_TYPE.getCode());
                }
            }
            //查询供应商库存变动涉及商品及店铺
            List<Map<String, Object>> supplierStoreInvolved = slOrderStreamMapper.getSupplierStoreInvolved(createTime);
            for (Map<String, Object> supplierShopId : supplierStoreInvolved) {
                //出库总数
                Map<String, Object> supplierTotalIssue = slOrderStreamMapper.totalIssue(Convert.toInt(supplierShopId.get("shopId")), createTime,2);
                //入库总数
                Map<String, Object> supplierTotalWarehousing = slOrderStreamMapper.totalWarehousing(Convert.toInt(supplierShopId.get("shopId")),createTime, 2);
                //查询每天不同规格的库存
                QueryWrapper<SlOrderStream> queryWrapper = this.streamQueryWrapper(supplierShopId,createTime);
                List<SlOrderStream> orderStreams = slOrderStreamMapper.selectList(queryWrapper);
                BigDecimal stockTotalAmount=new BigDecimal(0);
                int stock=0;
                SlOrderStream slOrderStream=new SlOrderStream();
                for (SlOrderStream orderStream:orderStreams){
                    //查询每日的最后一条作为当天的当前数量
                    SlOrderStream supplierLastUpdateData = slOrderStreamMapper.getLastUpdateData(Convert.toInt(supplierShopId.get("shopId")),orderStream.getRepoSpecId(),createTime,2);
                    BigDecimal round = round(supplierLastUpdateData.getCostPrice().multiply(Convert.toBigDecimal(supplierLastUpdateData.getRepoCountAf())), 2);
                    stockTotalAmount=stockTotalAmount.add(round);
                    stock+=supplierLastUpdateData.getRepoCountAf();
                    slOrderStream.setShopId(supplierLastUpdateData.getShopId());
                    slOrderStream.setShopName(supplierLastUpdateData.getShopName());
                    slOrderStream.setCreateTime(supplierLastUpdateData.getCreateTime());
                }
                slOrderStream.setRepoCountAf(stock);
                //添加专卖店合计数据
                this.addInventoryTotalData(slOrderStream, supplierTotalIssue, supplierTotalWarehousing, stockTotalAmount, 2);
                List<SlOrderStream> slOrderStreams = this.getOrderStream(supplierShopId,createTime,2);
                for (SlOrderStream orderStream : slOrderStreams) {
                    this.addStockControlData(orderStream, FactoryStockEnum.FACTORY_STOCK_TYPE.getCode());
                }

            }
            message.setCode(Status.successCode);
            message.setSuccess(true);
            message.setMessage(Status.success);
            log.info("定时同步库存管理任务执行完成!");
        } catch (Exception e) {
            log.error("定时同步库存管理任务执行失败，原因{}", e.getMessage());
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage(Status.fail);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return message;
    }

    public QueryWrapper<SlOrderStream> streamQueryWrapper(Map<String, Object> shopId,String createTime){
        QueryWrapper<SlOrderStream> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",shopId.get("shopId"));
        queryWrapper.likeRight("create_time",createTime);
        queryWrapper.eq("deleted",0);
        queryWrapper.groupBy("repo_spec_id");
        return queryWrapper;
    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage PageExclusiveShop(PageExclusiveShopParam param) throws ParseException {
        BusinessMessage message = new BusinessMessage();
        QueryWrapper<SlStoreInventoryTotal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", FactoryStockEnum.STORE_TYPE.getCode());
        queryWrapper.eq("deleted", FactoryStockEnum.DELETED.getCode());
        if (ObjectUtils.isNotEmpty(param.getShopId())) {
            queryWrapper.eq("shop_id", param.getShopId());
        }
        if (ObjectUtils.isNotEmpty(param.getShopName())) {
            queryWrapper.likeRight("shop_name", param.getShopName());
        }
        if (ObjectUtils.isNotEmpty(param.getTransactionTime())) {
            Date parse = DateUtils.ymd.parse(param.getTransactionTime());
            String format = DateUtils.ymd.format(parse);
            queryWrapper.likeRight("transaction_time", format);
        }
        queryWrapper.orderByDesc("transaction_time");
        Page<SlStoreInventoryTotal> slStoreInventoryTotalPage = slStoreInventoryTotalMapper.selectPage(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
        message.setData(slStoreInventoryTotalPage);
        message.setCode(Status.successCode);
        message.setSuccess(true);
        message.setMessage(Status.success);
        return message;
    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage PageStockLog(PageStockLogParam param) throws ParseException {
        BusinessMessage message = new BusinessMessage();
        if (ObjectUtils.isEmpty(param.getShopId())){
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage("请求参数不完整!");
            return message;
        }
        if (ObjectUtils.isNotEmpty(param.getTransactionTime())){
            Date parse = DateUtils.ymd.parse(param.getTransactionTime());
            String format = DateUtils.ymd.format(parse);
            param.setTransactionTime(format);
        }
        QueryWrapper<SlShopStockControl> queryWrapper = this.queryWrapper(param);
        queryWrapper.orderByDesc("transaction_time");
        Page<SlShopStockControl> slShopStockControlPage = slShopStockControlMapper.selectPage(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
        Map<String,Object> totalIssue=slShopStockControlMapper.totalIssue(param);
        Map<String,Object> totalReceipt=slShopStockControlMapper.totalReceipt(param);

        Map<String,Object> availableInventory=slShopStockControlMapper.availableInventory(param);
        Map<Object, Object> map = new HashMap<>();
        if (ObjectUtils.isNotEmpty(totalIssue)){
            map.put("totalIssue",totalIssue.get("quantity"));
        }else {
            map.put("totalIssue",0);
        }
        if (ObjectUtils.isNotEmpty(totalReceipt)){
            map.put("totalReceipt",totalReceipt.get("quantity"));
        }else {
            map.put("totalReceipt",0);
        }
        if (ObjectUtils.isNotEmpty(availableInventory)){
            map.put("availableInventory",availableInventory.get("availableStock"));
        }else {
            map.put("availableInventory",0);
        }
        map.put("slShopStockControlPage",slShopStockControlPage);
        message.setData(map);
        message.setCode(Status.successCode);
        message.setSuccess(true);
        message.setMessage(Status.success);
        return message;
    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage inventoryChangeLog(InventoryChangeLogParam param) {
        BusinessMessage message = new BusinessMessage();
        if (ObjectUtils.isEmpty(param.getType())){
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage("请求参数不完整!");
            return message;
        }
        QueryWrapper<SlShopStockControl> queryWrapper = this.inventoryChangeLogQueryWrapper(param);
        queryWrapper.orderByDesc("transaction_time");
        Page<SlShopStockControl> slShopStockControlPage = slShopStockControlMapper.selectPage(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
        message.setData(slShopStockControlPage);
        message.setCode(Status.successCode);
        message.setSuccess(true);
        message.setMessage(Status.success);
        return message;
    }

    public  QueryWrapper<SlShopStockControl> inventoryChangeLogQueryWrapper(InventoryChangeLogParam param){
        QueryWrapper<SlShopStockControl> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", FactoryStockEnum.STORE_TYPE.getCode());
        queryWrapper.eq("deleted", FactoryStockEnum.DELETED.getCode());
        if (ObjectUtils.isNotEmpty( param.getShopId())){
            queryWrapper.eq("shop_id", param.getShopId());
        }
        if (ObjectUtils.isNotEmpty(param.getShopName())) {
            queryWrapper.likeRight("shop_name", param.getShopName());
        }
        if (ObjectUtils.isNotEmpty(param.getSerialNumber())) {
            queryWrapper.eq("serial_number", param.getSerialNumber());
        }
        if (ObjectUtils.isNotEmpty(param.getDocumentNo())) {
            queryWrapper.eq("document_no", param.getDocumentNo());
        }
        if (ObjectUtils.isNotEmpty(param.getPurchaseShopName())) {
            queryWrapper.like("purchase_shop_name", param.getPurchaseShopName());
        }
        if (ObjectUtils.isNotEmpty(param.getType())) {
            if (param.getType().equals(FactoryStockEnum.OUTBOUND_DETAILS.getCode())) {
                queryWrapper.in("stock_type", 1,2);
            }
            if (param.getType().equals(FactoryStockEnum.WAREHOUSING_DETAILS.getCode())) {
                queryWrapper.in("stock_type", 3, 4);
            }
            if (param.getType().equals(FactoryStockEnum.PURCHASE_DETAILS.getCode())) {
                queryWrapper.in("stock_type", 3, 4);
                queryWrapper.in("business_type", 2);
            }
        }
        if (ObjectUtils.isNotEmpty(param.getStockType())) {
            queryWrapper.eq("stock_type", param.getStockType());
        }
        return queryWrapper;
    }

    public  QueryWrapper<SlShopStockControl> queryWrapper(PageStockLogParam param) throws ParseException {
        QueryWrapper<SlShopStockControl> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", FactoryStockEnum.STORE_TYPE.getCode());
        queryWrapper.eq("deleted", FactoryStockEnum.DELETED.getCode());
        if (ObjectUtils.isNotEmpty(param.getTransactionTime())) {
            queryWrapper.likeRight("transaction_time", param.getTransactionTime());
        }
        if (ObjectUtils.isNotEmpty( param.getShopId())){
            queryWrapper.eq("shop_id", param.getShopId());
        }
        if (ObjectUtils.isNotEmpty(param.getSerialNumber())) {
            queryWrapper.eq("serial_number", param.getSerialNumber());
        }
        if (ObjectUtils.isNotEmpty(param.getCreatedBeginTime()) && ObjectUtils.isNotEmpty(param.getCreatedEndTime())) {
            queryWrapper.ge("transaction_time", param.getCreatedBeginTime());
            queryWrapper.le("transaction_time", param.getCreatedBeginTime());
        }
        if (ObjectUtils.isNotEmpty(param.getStockType())) {
            queryWrapper.eq("stock_type", param.getStockType());
        }
        if (ObjectUtils.isNotEmpty(param.getProductId())){
            queryWrapper.eq("product_id",param.getProductId());
        }
        //成本明细使用，库存汇总几个key不用加该条件
        if (ObjectUtils.isNotEmpty(param.getBusinessType())) {
            if (param.getBusinessType().equals(1)){
                queryWrapper.eq("business_type", param.getBusinessType());
            }else{
                queryWrapper.in("business_type",2,3,4,5);
            }

        }
        return queryWrapper;
    }

    /**
     * @param shopId
     * @param createTime
     * @param type 1:专卖店 2:供应商
     * @return
     */
    public List<SlOrderStream> getOrderStream(Map<String, Object> shopId,String createTime,Integer type) {
        QueryWrapper<SlOrderStream> streamQueryWrapper = new QueryWrapper<>();
        streamQueryWrapper.eq("shop_id", Convert.toInt(shopId.get("shopId")));
        streamQueryWrapper.likeRight("create_time",createTime);
        if (type.equals(1)){
            streamQueryWrapper.in("shop_type",1,2);
        }else if (type.equals(2)){
            streamQueryWrapper.in("shop_type",3);
        }
        streamQueryWrapper.eq("deleted", FactoryStockEnum.DELETED.getCode());
        List<SlOrderStream> slOrderStreams = slOrderStreamMapper.selectList(streamQueryWrapper);
        return slOrderStreams;
    }

    /**
     * 添加库存总计数据
     *
     * @param lastUpdateData   每日的最后一条作为当天的当前数量
     * @param totalIssue       出库总数
     * @param totalWarehousing 入库总数
     * @param round            库存总金额
     * @param type             1、专卖店库存  2、供应商库存
     */
    @DataSource(name = "jyb_soole_data_hn")
    public void addInventoryTotalData(SlOrderStream lastUpdateData, Map<String, Object> totalIssue, Map<String, Object> totalWarehousing, BigDecimal round, int type) {
        SlStoreInventoryTotal inventoryTotal = new SlStoreInventoryTotal();
        inventoryTotal.setShopId(lastUpdateData.getShopId());
        inventoryTotal.setShopName(lastUpdateData.getShopName());
        inventoryTotal.setCurrentStock(lastUpdateData.getRepoCountAf());
        inventoryTotal.setAvailableStock(lastUpdateData.getRepoCountAf());
        inventoryTotal.setDeliveryQuantity(Convert.toInt(totalIssue.get("orderCount")));
        inventoryTotal.setReceiptQuantity(Convert.toInt(totalWarehousing.get("orderCount")));
        inventoryTotal.setStockTotalAmount(round);
        inventoryTotal.setType(type);
        inventoryTotal.setTransactionTime(lastUpdateData.getCreateTime());
        slStoreInventoryTotalMapper.insert(inventoryTotal);
    }

    /**
     * 添加库存变动流水
     *
     * @param orderStream
     */
    @DataSource(name = "jyb_soole_data_hn")
    public void addStockControlData(SlOrderStream orderStream, Integer type) {
        log.info("id为：[{}],type为:{}",orderStream.getId(),type);
        //库存总金额
        BigDecimal stockTotalAmount = round(orderStream.getCostPrice().multiply(Convert.toBigDecimal(orderStream.getRepoCountAf())), 2);
        //成本总金额
        BigDecimal totalCostAmount = round(orderStream.getCostPrice().multiply(Convert.toBigDecimal(orderStream.getChangeCount())), 2);
        SlShopStockControl slShopStockControl = new SlShopStockControl();
        slShopStockControl.setShopId(orderStream.getShopId());
        slShopStockControl.setShopName(orderStream.getShopName());
        slShopStockControl.setCurrentStock(orderStream.getRepoCountAf());
        slShopStockControl.setAvailableStock(orderStream.getRepoCountAf());
        if (type.equals(FactoryStockEnum.STORE_TYPE.getCode())) {
            SlOrder slOrder = slOrderMapper.selectById(orderStream.getOrderId());
            QueryWrapper<SlOrderDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderStream.getOrderId());
            SlOrderDetail slOrderDetail = slOrderDetailMapper.selectOne(queryWrapper);
            if (orderStream.getChangeSource().equals(FactoryStockEnum.SALE.getCode())) {
                System.out.println("订单详情："+slOrder);
                SlUser slUser = slUserMapper.selectById(slOrder.getUserId());
                slShopStockControl.setQuantity(orderStream.getChangeCount());
                slShopStockControl.setBusinessType(FactoryStockEnum.COMMODITY_TRADING.getCode());
                slShopStockControl.setStockType(FactoryStockEnum.ISSUED.getCode());
                if (ObjectUtils.isNotEmpty(slUser)){
                    slShopStockControl.setPurchaseShopId(slUser.getId());
                    slShopStockControl.setPurchaseShopName(slUser.getNickName());
                }
                 slShopStockControl.setDocumentNo(ObjectUtils.isEmpty(slOrderDetail)?null:slOrderDetail.getShipNumber());
            }else {
                slShopStockControl.setQuantity(orderStream.getChangeCount());
                slShopStockControl.setStockType(FactoryStockEnum.DELIVERY_COMPLETED.getCode());
                 slShopStockControl.setDocumentNo(ObjectUtils.isEmpty(slOrderDetail)?null:slOrderDetail.getShipNumber());
                if (orderStream.getChangeSource().equals(0)) {
                    slShopStockControl.setBusinessType(FactoryStockEnum.FACTORY_PURCHASE.getCode());
                     if(slOrderDetail!=null){
                         SlbShop slbShop = slShopMapper.selectById(slOrderDetail.getShopId());
                         slShopStockControl.setPurchaseShopId(slOrderDetail.getShopId());
                         slShopStockControl.setPurchaseShopName(slbShop.getName());
                     }
                }else {
                    SlUser slUser = slUserMapper.selectById(slOrder.getUserId());
                    if (ObjectUtils.isNotEmpty(slUser)){
                        slShopStockControl.setPurchaseShopId(slUser.getId());
                        slShopStockControl.setPurchaseShopName(slUser.getNickName());
                    }
                    if (orderStream.getChangeSource().equals(2)) {
                        slShopStockControl.setBusinessType(FactoryStockEnum.REFUND.getCode());
                    }else if (orderStream.getChangeSource().equals(3)){
                        slShopStockControl.setBusinessType(FactoryStockEnum.PAYMENT_FAILED.getCode());
                    }else if (orderStream.getChangeSource().equals(4)){
                        slShopStockControl.setBusinessType(FactoryStockEnum.CANCELLATION_OF_ORDER.getCode());
                    }
                }
            }
            slShopStockControl.setSerialNumber(slOrder.getSerialNumber());
            slShopStockControl.setOrderId(orderStream.getOrderId());
            slShopStockControl.setRemarks(slOrderDetail.getBuyerMessage());
        }else if (type.equals(FactoryStockEnum.FACTORY_STOCK_TYPE.getCode())){
            if (orderStream.getChangeSource().equals(FactoryStockEnum.SALE.getCode())){
                SlOrder slOrder = slOrderMapper.selectById(orderStream.getOrderId());
                QueryWrapper<SlbShop> shopQueryWrapper = new QueryWrapper<>();
                shopQueryWrapper.eq("owner_id",slOrder.getUserId());
                SlbShop slbShop = slShopMapper.selectOne(shopQueryWrapper);
                QueryWrapper<SlOrderDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", orderStream.getOrderId());
                SlOrderDetail slOrderDetail = slOrderDetailMapper.selectOne(queryWrapper);
                slShopStockControl.setSerialNumber(slOrderDetail.getSerialNumber());
                slShopStockControl.setOrderId(orderStream.getOrderId());
                if (ObjectUtils.isNotEmpty(slbShop)){
                    slShopStockControl.setPurchaseShopId(slbShop.getId());
                    slShopStockControl.setPurchaseShopName(slbShop.getName());
                }
                slShopStockControl.setDocumentNo(slOrderDetail.getShipNumber());
                slShopStockControl.setBusinessType(FactoryStockEnum.COMMODITY_TRADING.getCode());
                slShopStockControl.setStockType(FactoryStockEnum.ISSUED.getCode());
                slShopStockControl.setRemarks(slOrderDetail.getBuyerMessage());
            }else if (orderStream.getChangeSource().equals(FactoryStockEnum.BUY.getCode())){
                slShopStockControl.setBusinessType(FactoryStockEnum.FACTORY_PURCHASE.getCode());
                slShopStockControl.setStockType(FactoryStockEnum.DELIVERY_COMPLETED.getCode());
            }else{
                SlOrder slOrder = slOrderMapper.selectById(orderStream.getOrderId());
                QueryWrapper<SlbShop> shopQueryWrapper = new QueryWrapper<>();
                shopQueryWrapper.eq("owner_id",slOrder.getUserId());
                SlbShop slbShop = slShopMapper.selectOne(shopQueryWrapper);
                if (ObjectUtils.isNotEmpty(slbShop)){
                    slShopStockControl.setPurchaseShopId(slbShop.getId());
                    slShopStockControl.setPurchaseShopName(slbShop.getName());
                }
                slShopStockControl.setSerialNumber(slOrder.getSerialNumber());
                slShopStockControl.setOrderId(orderStream.getOrderId());
                slShopStockControl.setBusinessType(FactoryStockEnum.CANCELLATION_OF_ORDER.getCode());
                slShopStockControl.setStockType(FactoryStockEnum.DELIVERY_COMPLETED.getCode());
            }
            slShopStockControl.setQuantity(orderStream.getChangeCount());
        }
        slShopStockControl.setStockTotalAmount(stockTotalAmount);
        slShopStockControl.setType(type);
        slShopStockControl.setTransactionTime(orderStream.getCreateTime());
        slShopStockControl.setProductId(orderStream.getProductId());
        slShopStockControl.setProductName(orderStream.getProductName());
        slShopStockControl.setCostPrice(orderStream.getCostPrice());
        slShopStockControl.setRepositoryId(orderStream.getRepoSpecId());
        slShopStockControl.setProductDetailGroupName(orderStream.getRepoGroupName());
        slShopStockControl.setTotalCostAmount(totalCostAmount);
        slShopStockControlMapper.insert(slShopStockControl);
    }
}
